package com.hue.netty.day02.one;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;

/*
    netty的心跳检测机制
 */
public class Server {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //跟bossGroup添加日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            /*
                                IdleStateHandler是netty提供的处理空闲状态的处理器
                                readerIdleTime：这个时间内没有读事件，就会向客户端发送心跳检测包检测客户端是否连接
                                writerIdleTime：这个时间内没有写事件，就会向客户端发送心跳检测包检测客户端是否连接
                                allIdleTime：这个时间内没有读写事件，就会向客户端发送心跳检测包检测客户端是否连接
                                当IdleStateHandler的事件被触发之后，就会传递给管道的下一个handler去处理(调用userEventTriggered)
                             */
                            socketChannel.pipeline().
                                    addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS)).
                                    addLast(new MyHandler());  //添加自定义Handler去处理IdleStateHandler触发的事件
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7777).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
